package main

import (
	"context"
	"fmt"
	"github.com/ClickHouse/clickhouse-go/v2"
	"github.com/google/uuid"
	"log"
	"math/rand"
	"time"
)

type Config struct {
	Clickhouse struct {
		Host string `json:"host"`
		Port string `json:"port"`
		User string `json:"user"`
		Pass string `json:"password"`
		DB   string `json:"database"`
	} `yaml:"clickhouse"`
}

func main() {
	// 1. 初始化随机种子 生成随机数
	rand.Seed(time.Now().UnixNano())

	cfg := Config{
		Clickhouse: struct {
			Host string `json:"host"`
			Port string `json:"port"`
			User string `json:"user"`
			Pass string `json:"password"`
			DB   string `json:"database"`
		}(struct {
			Host string `yaml:host`
			Port string `yaml:port`
			User string `yaml:user`
			Pass string `yaml:password`
			DB   string `yaml:database`
		}{
			Host: "localhost", Port: "9000", User: "default", Pass: "", DB: "default"}),
	}
	// 3. 连接ClickHouse
	conn, err := clickhouse.Open(&clickhouse.Options{
		Addr: []string{cfg.Clickhouse.Host + ":" + cfg.Clickhouse.Port},
		Auth: clickhouse.Auth{
			Database: cfg.Clickhouse.DB,
			Username: cfg.Clickhouse.User,
			Password: cfg.Clickhouse.Pass,
		},
		//Debug: true,
	})
	if err != nil {
		panic(err)
	}

	defer conn.Close()
	// 4. 准备随机数据生成器
	status := []string{"OPEN", "IN_PROGRESS", "RESOLVED", "CLOSED", "REOPENED"}
	assignees := []string{
		"john.doe", "jane.smith", "mike.johnson", "sarah.williams", "david.brown",
		"emily.davis", "robert.miller", "lisa.wilson", "thomas.moore", "jennifer.taylor",
	}

	operators := []string{"system", "admin", "automation", "user1", "user2"}
	descriptions := []string{
		"Server issue", "Database problem", "Network outage", "API failure",
		"Performance degradation", "Security vulnerability", "UI bug", "Feature request",
		"Configuration change", "Data migration",
	}

	// 5. 生成并插入1000条随机工单数据

	startTime := time.Now()
	batchSize := 100
	totalRecords := 1000

	for i := 0; i < totalRecords; i += batchSize {
		currentBatchSize := batchSize
		if i+currentBatchSize > totalRecords {
			currentBatchSize = totalRecords - i
		}
		// 准备批量插入
		batch, err := conn.PrepareBatch(context.Background(), "INSERT INTO ticket_logs")
		if err != nil {
			panic(err)
		}
		for j := 0; j < currentBatchSize; j++ {
			// 生成随机数据
			ticketID := fmt.Sprintf("TICKET-%04d", i+j+1)

			status := status[rand.Intn(len(status))]
			assignee := assignees[rand.Intn(len(assignees))]
			operator := operators[rand.Intn(len(operators))]
			description := descriptions[rand.Intn(len(descriptions))]

			// 随机日期：过去30天到未来30天
			daysOffset := rand.Intn(60) - 30
			dueDate := time.Now().AddDate(0, 0, daysOffset)

			// 随机操作时间：过去7天内
			opDaysOffset := rand.Intn(7)
			opHoursOffset := rand.Intn(24)
			operationTime := time.Now().AddDate(0, 0, -opDaysOffset).Add(-time.Hour * time.Duration(opHoursOffset))

			// 随机操作类型
			operation := "CREATE"
			if i > 0 && rand.Intn(10) > 7 { // 30%的概率生成UPDATE操作
				operation = "UPDATE"
			}

			// 添加到批量
			err = batch.Append(
				uuid.New(),    // id
				ticketID,      // ticket_id
				status,        // status
				dueDate,       // due_date
				assignee,      // assignee
				operation,     // operation
				operationTime, // operation_time
				operator,      // operator
				description,   // details
			)
			if err != nil {
				log.Fatalf("Failed to append to batch: %v", err)
			}
		}
		// 执行批量插入
		if err := batch.Send(); err != nil {
			log.Fatalf("Failed to send batch: %v", err)
		}
		fmt.Printf("Inserted batch %d-%d\n", i+1, i+currentBatchSize)
	}
	// 6. 输出统计信息
	elapsed := time.Since(startTime)
	fmt.Printf("\nSuccessfully inserted %d records in %s\n", totalRecords, elapsed)

}
